<!-- 发起实习评价页面 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="发起实习评价" :showBack="true"></pageHeaderNew>
    </template>
    <div class="main">
      <div class="hear">
        <a-steps changeable :current="current" @change="setCurrent">
          <a-step description="">评价基础信息 </a-step>
          <a-step description="">编辑评价方案内容 </a-step>
        </a-steps>
      </div>
      <div class="business" v-show="current === 1">
        <a-form
          ref="formRef"
          :model="formData.data"
          auto-label-width
          :style="{ width: '600px', margin: 'auto' }"
          :rules="rules"
        >
          <a-form-item field="userName" label="被评价人" required show-colon>
            <a-input v-model="formData.data.userName" disabled />
          </a-form-item>
          <a-form-item field="name" label="评价方案名称" required show-colon>
            <a-input
              v-model="formData.data.name"
              placeholder="请输入"
              disabled
            />
          </a-form-item>
          <a-form-item
            required
            field="templateId"
            label="选择实习评价模板"
            show-colon
          >
            <a-select
              @change="templatechange"
              v-model="formData.data.templateId"
              :style="{ width: '320px' }"
            >
              <a-option
                v-for="item in templateList"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="评价描述" show-colon>
            <a-textarea
              v-model="formData.data.remark"
              placeholder="请输入"
              style="height: 200px"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            label="评价截止时间"
            show-colon
            help="温馨提醒：过评价截止时间，默认实习评价是不通过。"
          >
            <a-date-picker
              show-time
              format="YYYY-MM-DD HH:mm "
              v-model="formData.data.endDate"
            />
          </a-form-item>
        </a-form>
      </div>
      <div v-show="current === 2">
        <FormSetting
          ref="formSettigRef"
          v-model:data="formData.data.templateData"
          :isSend="true"
        ></FormSetting>
      </div>
    </div>

    <footer>
      <a-space>
        <a-button
          v-show="current !== 1"
          @click="current = --current"
          class="btn"
          >上一步</a-button
        >
        <a-button
          type="primary"
          class="btn"
          v-show="current === 1"
          @click="next"
          >下一步</a-button
        >
        <a-button
          type="primary"
          class="btn"
          v-show="current === 2"
          @click="save"
          >保存</a-button
        >
        <a-button
          type="primary"
          class="btn"
          v-show="current === 2"
          @click="send"
          >确认发起</a-button
        >
      </a-space>
    </footer>
  </ContentCard>
</template>
<script setup lang="ts">
// import eventFrom from './eventFrom';
import clonedeep from 'lodash.clonedeep';
import { useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import {
  GetInternshipEvaluationList,
  GetInternshipEvaluationDetail
} from '@/apis/management/human/baseSetting/internshipSetting/index';
import {
  PostInternshipEvaluationHuman,
  PutInternshipEvaluationHuman,
  GetInternshipEvaluationHumanDetail,
  DelInternshipEvaluationHumanDetail,
  ChangeInternshipEvaluationHumanStatus
} from '@/apis/management/human/humanChange/internship';
import { getHumanDetail } from '@/utils/common';
import FormSetting from './Components/FromSetting/index.vue';

const visibleEvent = ref(false);
const router = useRouter();
const route = useRoute();
const userId = +route.query.id || localStorage.getItem('userId');
let formRef = ref();
let formSettigRef = ref();
const rules = {
  userName: [
    {
      required: true,
      message: '请输入'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入'
    }
  ],
  templateId: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

const current = ref(1);

const setCurrent = async (index: number) => {
  current.value = index;
  if (current.value > 1) {
    if (await formRef.value.validate()) {
      current.value = 1;
      return Message.error('请填写必填项');
    }
  }
};
const formData = reactive({
  data: {
    userName: '',
    name: '',
    remark: '',
    templateId: undefined,
    endDate: '',
    evaluateStatus: 1, // 0 未发起 1 保存 2提交
    userId: userId,
    // 模板详情
    templateData: {
      organizationEvaluation: 100,
      selfEvaluation: 0,
      upperLimitType: 2,
      scoreCalculation: 1,
      indexArr: [], // 指标表格
      customArr: [] // 自定义表格
    }
  }
});
const next = async () => {
  current.value = Math.min(2, current.value + 1);
  if (current.value > 1) {
    if (await formRef.value.validate()) {
      current.value = 1;
      return Message.error('请填写必填项');
    }
  }
};

let templateList = ref([]);
let humanDetail = ref();
const getData = async () => {
  try {
    const [HumanTemplateDetailRes, HumanDetailRes, templateListRes] =
      await Promise.all([
        GetInternshipEvaluationHumanDetail({
          id: userId
        }),
        getHumanDetail(userId),
        GetInternshipEvaluationList({
          pageNumber: 0,
          pageSize: -1
        })
      ]);
    humanDetail.value = HumanDetailRes;
    templateList.value = templateListRes.content.filter(
      (el: any) => el.enable === 1
    );
    const templateDataEnum = [
      'organizationEvaluation',
      'selfEvaluation',
      'upperLimitType',
      'upperLimitScore',
      'selfEvaluation',
      'scoreCalculation',
      'indexArr',
      'customArr'
    ];
    if (HumanTemplateDetailRes.id) {
      for (let i in HumanTemplateDetailRes) {
        if (templateDataEnum.includes(i)) {
          formData.data.templateData[i] = HumanTemplateDetailRes[i];
        } else {
          formData.data[i] = HumanTemplateDetailRes[i];
        }
      }
    }
    formData.data.userName = humanDetail.value.name;
    formData.data.name = `${humanDetail.value.name}的实习评价`;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

const templatechange = async (id: number) => {
  try {
    const res = await GetInternshipEvaluationDetail({
      id
    });
    formData.data.templateData = res;
    formData.data.remark = res.remark;
    // 默认第一条为实习综合评价
    formData.data.templateData.customArr.unshift({
      name: '实习综合评价',
      text: ''
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 保存
const save = async () => {
  try {
    if (await formSettigRef.value.validate()) return;
    let data = clonedeep(formData.data);
    if (data.id) {
      data.evaluateStatus = 1;
      delete data.templateData?.remark;
      data = {
        ...data,
        ...data.templateData
      };
      await handleDel();
      await PutInternshipEvaluationHuman(data);
      await ChangeInternshipEvaluationHumanStatus({
        id: userId,
        status: 1
      });
    } else {
      data.evaluateStatus = 1;
      data = handleData(data);
      await PostInternshipEvaluationHuman(data);
      await ChangeInternshipEvaluationHumanStatus({
        id: userId,
        status: 1
      });
    }
    Message.success('保存成功！');
  } catch (error: unknown) {
    console.log(error);
  }
};

// 发起
const send = async () => {
  try {
    if (await formSettigRef.value.validate()) return;
    let data = clonedeep(formData.data);
    if (data.id) {
      data.evaluateStatus = 2;
      delete data.templateData?.remark;
      data = {
        ...data,
        ...data.templateData
      };
      await handleDel();
      await PutInternshipEvaluationHuman(data);
      await ChangeInternshipEvaluationHumanStatus({
        id: userId,
        status: 2
      });
    } else {
      data.evaluateStatus = 2;
      data = handleData(data);
      await PostInternshipEvaluationHuman(data);
      await ChangeInternshipEvaluationHumanStatus({
        id: userId,
        status: 2
      });
    }
    Message.success('发起成功！');
  } catch (error: unknown) {
    console.log(error);
  }
};

// 处理从评价模板过来数据的id
const handleData = (data: any) => {
  delete data.templateData?.id;
  delete data.templateData?.remark;
  data.templateData.indexArr = data.templateData?.indexArr.map((el: any) => {
    delete el.id;
    return el;
  });
  data.templateData.customArr = formData.data.templateData?.customArr.map(
    (el: any) => {
      delete el.id;
      return el;
    }
  );
  const temp = { ...data.templateData };
  delete data.templateData;
  data = { ...data, ...temp };
  return data;
};

// 处理编辑时删除id
const handleDel = async () => {
  if (formSettigRef.value.delTypeIds.type2Ids.length > 0) {
    await DelInternshipEvaluationHumanDetail({
      ids: formSettigRef.value.delTypeIds.type2Ids,
      type: 2
    });
  }
  if (formSettigRef.value.delTypeIds.type3Ids.length > 0) {
    await DelInternshipEvaluationHumanDetail({
      ids: formSettigRef.value.delTypeIds.type3Ids,
      type: 3
    });
  }
  if (formSettigRef.value.delTypeIds.type4Ids.length > 0) {
    await DelInternshipEvaluationHumanDetail({
      ids: formSettigRef.value.delTypeIds.type4Ids,
      type: 4
    });
  }
};
</script>
<style lang="less" scoped>
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}

:deep(.arco-steps) {
  width: 400px;
  margin: 0 auto;
  margin-bottom: 40px;
}
</style>
